<template>
  <div>
      <el-dialog title="奖金分配" :close-on-click-modal="false" :visible.sync="visible" v-if="visible" :fullscreen="true" @close="callback">
          <el-tabs type="card" v-model="activeName" @tab-click="handleClick" class="tabBox">
              <el-tab-pane label="机构分组" name="second" class="cpTable"></el-tab-pane>
              <el-tab-pane label="人员分组" name="first" class="cpTable"></el-tab-pane>
              <!-- <el-tab-pane label="定向分配" name="third" class="cpTable"></el-tab-pane> -->
               <el-row :gutter="10">
                 <el-col :span="24" style="margin-bottom:20px" v-if="activeName!='third'">
                     <el-button type="primary" plain @click="keepMoBan">该分配保存模板</el-button>
                     <el-button type="primary" plain @click="diaoyong">调用上一个模板</el-button>
                     <el-button type="primary" plain @click="editFeip">总额修改</el-button>
                     <div style="float:right">
                         <el-button type="primary" plain @click="keepTable">模拟测试</el-button>
                         <!-- <el-button type="primary" plain>提交</el-button> -->
                         <!-- <el-button type="warning" plain @click="yufenpei">预分配</el-button> -->
                     </div>
                 </el-col>
                <div class="boxsty zhiBiao popover-style-parent-div" v-if="activeName!='third'">
                    <el-col :span="24">
                        <el-form :model="form">
                            <el-col :span="24" v-if="activeName=='second'">
                                <el-col :span="20" :style="{height: colHeightThree,overflow:'hidden'}">
                                    <div>
                                        <el-form-item label="机构分组:">
                                            <el-checkbox-group v-model="form.jigou" @change="jigouchange" :key="1">
                                                <el-checkbox v-for="ite in jigouList" :key="ite.id" :label="ite.id">{{ite.jgFzName}}</el-checkbox>
                                            </el-checkbox-group>
                                        </el-form-item>
                                    </div>
                                </el-col>
                                <el-col :span="4">
                                  <el-popover
                                    placement="bottom-end"
                                    title="机构分组"
                                    width="900"
                                    trigger="manual"
                                    v-model="visiblePopover3">
                                    <el-form-item>
                                      <el-checkbox-group v-model="form.jigou" @change="jigouchange" :key="1">
                                        <el-checkbox v-for="ite in jigouList" :key="ite.id" :label="ite.id">{{ite.jgFzName}}</el-checkbox>
                                      </el-checkbox-group>
                                    </el-form-item>
                                    <el-button slot="reference" type="text" @click="visiblePopover3 = !visiblePopover3">更多<i :class="visiblePopover3?'el-icon-arrow-down':'el-icon-arrow-right'"></i></el-button>
                                  </el-popover>
<!--                                    <el-button type="text" @click="moreOne(3)">更多<i :class="colHeightshowThree?'el-icon-arrow-down':'el-icon-arrow-right'"></i></el-button>-->
                                    <el-button type="primary" plain @click="add_jigougrouping($event)">添加分组</el-button>
                                </el-col>
                            </el-col>
                            <el-col :span="24" v-if="activeName=='first'">
                                <el-col :span="20" :style="{height: colHeightOne,overflow:'hidden'}">
                                    <div>
                                        <el-form-item label="人员分组:" :key="2">
                                            <el-checkbox-group v-model="form.check" @change="renyuanchange">
                                                <el-checkbox v-for="item in checkList" :key="item.id" :label="item.id">{{item.ryfzMc}}</el-checkbox>
                                            </el-checkbox-group>
                                        </el-form-item>
                                    </div>
                                </el-col>
                                <el-col :span="4">
                                  <el-popover
                                    placement="bottom-end"
                                    title="人员分组"
                                    width="900"
                                    trigger="manual"
                                    v-model="visiblePopover1">
                                    <el-form-item :key="21">
                                      <el-checkbox-group v-model="form.check" @change="renyuanchange">
                                        <el-checkbox v-for="item in checkList" :key="item.id" :label="item.id">{{item.ryfzMc}}</el-checkbox>
                                      </el-checkbox-group>
                                    </el-form-item>
                                    <el-button slot="reference" type="text" @click="visiblePopover1 = !visiblePopover1">更多<i :class="visiblePopover1?'el-icon-arrow-down':'el-icon-arrow-right'"></i></el-button>
                                  </el-popover>
<!--                                    <el-button type="text" @click="moreOne(1)">更多<i :class="colHeightshow?'el-icon-arrow-down':'el-icon-arrow-right'"></i></el-button>-->
                                    <el-button type="primary" plain @click="add_grouping($event)">添加分组</el-button>
                                </el-col>
                            </el-col>
                            <el-col :span="24">
                                <el-col :span="20" :style="{height: colHeightTwo,overflow:'hidden'}">
                                    <el-form-item label="奖金分配:">
                                        <el-checkbox-group v-model="form.bonus" @change="handleCheckedCitiesChange">
                                            <el-checkbox v-for="item in bonusList" :key="item.id" :label="item.id">{{item.jjxMc}}</el-checkbox>
                                        </el-checkbox-group>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="4">
                                  <el-popover
                                    placement="bottom-end"
                                    title="奖金分配"
                                    width="900"
                                    trigger="manual"
                                    v-model="visiblePopover2">
                                    <el-form-item>
                                      <el-checkbox-group v-model="form.bonus" @change="handleCheckedCitiesChange">
                                        <el-checkbox v-for="item in bonusList" :key="item.id" :label="item.id">{{item.jjxMc}}</el-checkbox>
                                      </el-checkbox-group>
                                    </el-form-item>
                                    <el-button slot="reference" type="text" @click="visiblePopover2 = !visiblePopover2">更多<i :class="visiblePopover2?'el-icon-arrow-down':'el-icon-arrow-right'"></i></el-button>
                                  </el-popover>
<!--                                    <el-button type="text" @click="moreOne(2)">更多<i :class="colHeightshowtwo?'el-icon-arrow-down':'el-icon-arrow-right'"></i></el-button>-->
                                    <el-button type="primary" plain @click="addOrUpdateHandle()">添加奖金</el-button>
                                </el-col>

                            </el-col>

                            <el-col :span="24">
                                <!-- <el-button type="primary" plain @click="addConfirm()">清楚选项</el-button> -->
                                    <el-button type="warning" plain @click="fenPei()">添加</el-button>
                            </el-col>
                        </el-form>
                    </el-col>
                </div>
                <el-col :span="24" style="margin-top:30px">
                    <el-col :span="24" v-if="activeName=='third'" style="text-align:right;margin-bottom:20px">
                        <el-button type="primary"plain>保存</el-button>
                    </el-col>
                    
                    <el-col :span="24"  v-show="activeName=='first'">
                        <renYuanTable :key="isRen" ref="renYuanTableRef" :fromJg="fromJg" @renTableChild="renTableChild"></renYuanTable>
                     </el-col>
                     <el-col :span="24"  v-show="activeName=='second'">
                         <!--部门选奖金-->
                        <buMenTable :key="isJi" ref="buMenTableRef" :fromRy="fromRy" @buTableChild="buTableChild"></buMenTable> 
                     </el-col>
                     <el-col :span="11" style="float:right;margin-top:20px;" v-if="activeName!='third'">
                         
                        
                         <!-- <el-table
                            ref="zhibiaotable"
                            style="width: 100%;"
                            :data="dataList"
                            :summary-method="getSummaries"
                            show-summary
                            border
                            v-loading="dataListLoading">
                            <el-table-column
                                label="序号"
                                type="index"
                                width="55">
                            </el-table-column>
                            <el-table-column
                                label="奖金项"
                                prop="jjxMc"
                                min-width="100">
                            </el-table-column>
                            <el-table-column
                                label="总部部门（合计金额"
                                prop="jjxJe"
                                min-width="200">
                                <template slot="header" slot-scope="scope">
                                    <span>总部部门（合计金额)</span>
                                    <span style="margin-left:40px;" v-if="activeName=='first'">可剩余金额:{{jjYe}}</span>
                                  <span style="margin-left:40px;"  v-else-if="activeName=='second'">可剩余金额:{{jjYeTwo}}</span>
                                </template>
                                <template slot-scope="scope">
                                    <span>{{scope.row.jjxJe}}</span>
                                </template>
                            </el-table-column>

                         </el-table> -->
                     </el-col>
                    </el-col>

                <el-col v-if="activeName!='third'" :span="24" style="margin-top:20px;">
                     <el-form :model="dataForm">
                    <el-col :span="10">
                       
                            <el-form-item label="请于">
                                <el-date-picker
                                    :disabled='true'
                                    v-model="gqTime"
                                    type="date"
                                    format='yyyy-MM-dd'
                                    style="width:160px"
                                    value-format='yyyy-MM-dd'
                                    placeholder="选择日期">
                                </el-date-picker>
                                完成奖金上报工作
                            </el-form-item>
                        
                    </el-col>
                    <el-col :span="8">
                                <el-form-item label="具体工作要求">
                                    <el-upload
                                        class="upload-demo"
                                        action=""
                                        :on-success="handleSuccess"
                                        :on-remove="handleRemove"
                                        :file-list="fileList">
                                        <el-button size="small" type="primary">上传附件</el-button>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="8">
                                <el-button type="primary" plain>保存</el-button>
                            </el-col>
                    <!-- <el-col :span="10" style="text-align:right;float:right">
                         <div>
                             <span style="margin-right:20px;">剩余可分配金额:4444</span>

                        </div>
                    </el-col> -->
                     </el-form>
                </el-col>
               
            </el-row>

          </el-tabs>

      </el-dialog>
      <!--人员分组-->
      <groupEditingForm ref='groupEditingRef' @refreshDataList="refreshDataList"></groupEditingForm>
      <!--新的奖金分配---->
      <el-dialog title="奖金分配"  width="90vw" height="90vh" top="5vh" append-to-body :close-on-click-modal="false" :visible.sync="jiangVisible" v-if="jiangVisible"  @close="callbackTwo">
          <jiangjinxiangTable ref="jiangjinxiangRef" @jiangjinxChild="jiangjinxChild"></jiangjinxiangTable>

      </el-dialog>
     
      <!-- 添加人员分组 -->
      <tableForm ref="tableForm" @refreshDataList="refreshDataList"></tableForm>
      <!-- 奖金新增-->
      <jiangTableForm v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="refreshDataList"></jiangTableForm>
      <!--预分配-->
      <yufenpeiForm ref="yufenpeiRef" @getChildValue='getChildValue'></yufenpeiForm>
      <!--添加机构-->
      <jigoutableForm ref="jigoutableRef" @refreshDataList="refreshDataList"></jigoutableForm>
      <!--调用模板-->
      <mubanTable ref="mubanTableRef" @mubanTableChild='mubanTableChild'></mubanTable>
      <jjxgfpTableForm v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="refreshDataList"></jjxgfpTableForm>
  </div>
</template>

<script>

import groupEditingForm from '@/views/jiangjin/jiangjinfpjjfpdjb/groupEditing-form'
import jiangjinfpjjfpdjbFpGrxx from '@/views/jiangjin/jiangjinfpjjfpdjb/jiangjinfpjjfpdjb-fp-grxx'


import {getRyfzbList,updateGrNew,getJgfzList,updateBmNew,saveTemplate,pageTemplate} from "@/api/jiangjin/jiangjinryfzb"
import {getJjDeptJjx} from "@/api/jiangjin/jiangjinjjxxxb"
import tableForm from '@/views/jiangjin/jiangjinryfzb/jiangjinryfzb-form'
import jiangTableForm from '@/views/jiangjin/jiangjinjjxxxb/jiangjinjjxxxb-form'
import jiangjinxiangTable from '@/views/jiangjin/jiangjinfpjjfpdjb/jiangjinxiang-table'
import yufenpeiForm from '@/views/jiangjin/jiangjinfpjjfpdjb/yufenpei-form'
import jigoutableForm from '@/views/jiangjin/jiangjinjjjgfz/jiangjinjjjgfz-form'
import mubanTable from '@/views/jiangjin/jiangjinfpjjfpdjb/muban-table'
import {getObj, putObj, updateGr} from '@/api/jiangjin/jiangjinfpjjfpdjb'
import buMenTable from '@/views/jiangjin/jiangjinfpjjfpdjb/buMen-table'
import renYuanTable from '@/views/jiangjin/jiangjinfpjjfpdjb/renYuan-table'
import jjxgfpTableForm from '@/views/jiangjin/jiangjinfpjjfpdjb/jiangjinfpjjfpdjb-form'
export default {
  components: {
      groupEditingForm,
      jiangjinfpjjfpdjbFpGrxx,
      tableForm,
      jiangTableForm,
      jiangjinxiangTable,
      yufenpeiForm,
      jigoutableForm,
      mubanTable,
      buMenTable,
      renYuanTable,
      jjxgfpTableForm
   },
    name:"jiangjinxinfpryfz",
    data(){
        return{
            activeName:"second",
            visible:false,
            showForm:true,
            form:{
                check:[],
                bonus:[],
                jigou:[],
                bonus2:[]
            },
            spanArr: [],
            spanArrTwo:[],
            pos:0,
            postwo:0,
            checkList:[],
            bonusList:[],
            tableList:[],
            dataList:[],
            dataListLoading:false,
            dataForm:{
                yue:"",
                value2:""
            },
            value:"",
            fileList:[],
            jiangSe:"",
            options: [{
            value: '优秀员工奖',
            label: '优秀员工奖'
            }, {
            value: '安全保卫奖',
            label: '安全保卫奖'
            }],
            name:"",
            amount:"",
            optionsTwo:[
                {
                value: '人员分组1',
                label: '人员分组1'
                }, {
                value: '人员分组2',
                label: '人员分组2'
                }
            ],
            jjfpId:"",
            jiangVisible:false,
            showSapn:12,
            tableData: [],
            fen:"",
            multipleSelection:[],
            deptId:"",
            addOrUpdateVisible: false,
            chongXuan:false,
            valueList:[],
            headFilters:[],
            tableDataOld:[],
            colHeightOne:"40px",
            colHeightTwo:"40px",
            colHeightThree:"40px",
            colHeightshow:false,
            colHeightshowtwo:false,
            colHeightshowThree:false,
            visiblePopover1:false,
            visiblePopover2:false,
            visiblePopover3:false,
            jigouList:[],
            tableDataTwo:[],
            tableDataOldTwo:[],
            multipleSelectionTwo:[],
            jjYe:0,
            jjYeTwo:0,
            jjYeThree:0,
            jjYeFour:0,
            sfCeff:"",
            checkListTwo:[],
            num1:0,
            num2:0,
            valueListTwo:[],
            bmJj:0,
            ygJj:0,
            chuData:{},
            buList:[],
            renList:[],
            jgze:0,
            ryze:0,
            rydsJiang:0,
            jgdsJiang:0,
            fromRy:{},
            fromJg:{},
            isRen:false,
            isJi:false,
            gqTime:""
        }
    },
     mounted: function() {
        this.getSpanArr(this.tableData);
        this.getSpanArr(this.tableDataTwo);
    },
    methods:{
        init(data){
          //console.log("data:"+JSON.stringify(data))
            this.getchudata(data.id)
            this.visible=true;
            this.jjfpId = data.id;
            this.deptId=data.jjDeptId;
            this.gqTime=data.gqTime;
            // if(this.activeName=='first'){
            //     this.jjYe=data.fpJj*1-data.bmJj*1;
            // }
            // if(this.activeName=='second'){
            //     this.jjYeTwo=data.fpJj*1-data.ygJj*1;
            // }
          // this.jjYe=data.fpJj*1-data.bmJj*1;
          // this.jjYeTwo=data.fpJj*1-data.ygJj*1;
         // this.jjYe=data.fpJj*1-data.bmJj*1-data.ygJj*1;
         //this.jjYeTwo=data.fpJj*1-data.ygJj*1-data.bmJj*1;
            this.bmJj=data.bmJj;
            this.ygJj=data.ygJj;
            //this.jjYeTwo=data.fpJj;
            this.jjYeThree=data.fpJj;
            this.jjYeFour=data.fpJj;
            this.sfCeff=data.sfCeff;
            this.getcheckList(this.deptId);
            this.addConfirm()
            
        },
        //修改分配
        editFeip(){
            this.addOrUpdateVisible=true
           ////console.log("this.jjfpId:"+this.jjfpId)
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init(this.jjfpId,'编辑')
            })
        },
        getchudata(id){
            getObj(id).then(res=>{
                this.chuData=res.data.data;
            
                this.chuData.jjxXq=JSON.parse(this.chuData.jjxXq).map(item=>{
                    item.tableData=[]
                    item.jjZe=JSON.parse(this.chuData.jjxJeXq)[item.jjxId].jjZe
                    item.jjYe=JSON.parse(this.chuData.jjxJeXq)[item.jjxId].jjYe
                    item.bmJj=JSON.parse(this.chuData.jjxJeXq)[item.jjxId].bmJj
                    item.ygJj=JSON.parse(this.chuData.jjxJeXq)[item.jjxId].ygJj
                    item.sum=0
                    return item
                })
                //console.log("初始化:"+JSON.stringify(this.chuData))
                this.buList=JSON.parse(JSON.stringify(this.chuData.jjxXq))
                //this.buList=Object.assign([],res.data.data.jjxXq)
                this.renList=JSON.parse(JSON.stringify(this.chuData.jjxXq))
                this.sfCeff=res.data.data.sfCeff
                this.$nextTick(()=>{
                    this.$refs.buMenTableRef.init(this.buList,this.jjfpId,this.deptId,this.activeName,this.sfCeff,this.gqTime);
                    this.$refs.renYuanTableRef.init(this.renList,this.jjfpId,this.deptId,this.activeName,this.sfCeff,this.gqTime)
                })
            })

        },
        //从机构子集传过来的数据
        buTableChild(buTableChild){
               if(buTableChild.fanH){
                
                   this.form.jigou=buTableChild.jg
                   this.form.bonus=buTableChild.jj
                   this.$refs.buMenTableRef.jiang(buTableChild.jg,this.jigouList)
                   this.$refs.buMenTableRef.jigoujiangjin(buTableChild.jj,this.bonusList)
               } 
            //清空选择
            if(buTableChild.qingK){
                this.addConfirm()
                this.form.jigou=buTableChild.jiIds;
            }
            if(buTableChild.qingJ){
                this.addConfirm()
            }
            //获取计算的金额
            if(buTableChild.jiSuan){
                var list=buTableChild.jgnum.map(item=>{
                    if(item.hasOwnProperty('sum')){
                        return item.sum*1
                    }else{
                        return 0
                    }
                    
                })
                this.jgdsJiang=buTableChild.dsJiang;
                this.jgze=this.sum(list)
                this.jjYe=this.jjYeThree*1-this.ryze*1-this.jgze*1; //-this.bmJj*1-this.ygJj*1
        
            }
            if(buTableChild.guan=="关闭"){
                this.callback()
            }
            // //反选奖金
            // if(buTableChild.fanXuan){
            //     this.form.bonus=[]
            //     this.form.bonus=this.uniqueTwo(buTableChild.jjxIds);
            // }
        },
        //去重
        uniqueTwo(arr) {
        for (var i = 0; i < arr.length; i++) {
            for (var j = i + 1; j < arr.length; j++) {
            if (arr[i] == arr[j]) {         //第一个等同于第二个，splice方法删除第二个
                arr.splice(j, 1);
                j--;
            }
            }
        }
        return arr;

        },
        //从人员分组子集传过来的数据
        renTableChild(renTableChild){
      
            //清空选择
            if(renTableChild.qingK){
                this.addConfirm()
            }
            //console.log("renTableChild:"+JSON.stringify(renTableChild))
            //获取计算的金额
            if(renTableChild.jiSuan){
                
                var list=renTableChild.jgnum.map(item=>{
                    if(item.hasOwnProperty('sum')){
                        return item.sum*1
                    }else{
                        return 0
                    }
                    
                })
                this.rydsJiang=renTableChild.dsJiang;
                this.ryze=this.sum(list)
                this.jjYe=this.jjYeThree*1-this.ryze*1-this.jgze*1;//this.bmJj*1-this.ygJj*1-
       
            }
            //关闭
            if(renTableChild.guan=="关闭"){
                this.callback()
            }
        },
        //从子集传过来的可剩余额
        kesheng(kesheng){
         //console.log(kesheng)
          if(kesheng!=0){
            if(this.activeName=='first'){
              this.ygJj=kesheng;
            }
            if(this.activeName=='second'){
              this.bmJj=kesheng;
            }
            const jjYe=(this.jjYeThree*1)-(this.bmJj*1)-(this.ygJj*1);
            const jjYeTwo=(this.jjYeThree*1)-(this.ygJj*1)-(this.bmJj*1);
            this.jjYe=jjYe.toFixed(2);
            this.jjYeTwo=jjYeTwo.toFixed(2);
          }
           //  if(kesheng==0){
           //      var tableData=this.activeName=='first'?this.tableData:this.tableDataTwo
           //      for(let j=0;j<tableData.length;j++){
           //          tableData[j].jjxJe=0
           //          this.blurJjxje(j)
           //      }
           // this.$nextTick(()=>{
           //      this.getSpanArrJiang(tableData);
           //      if(this.activeName=='first'){
           //        this.ygJj=kesheng;
           //          this.jjYe=this.jjYeThree*1-kesheng*1-this.bmJj*1
           //          this.tableData=tableData
           //      }
           //      if(this.activeName=='second'){
           //        this.bmJj=kesheng;
           //          this.jjYeTwo=this.jjYeThree*1-kesheng*1-this.ygJj*1
           //          this.tableDataTwo=tableData
           //      }
           //  })
           //  }else{
           //    if(this.activeName=='first'){
           //      this.ygJj=kesheng;
           //      //this.jjYe=this.jjYeThree*1-this.bmJj*1-this.ygJj*1;
           //      //this.jjYe=this.jjYeThree*1-kesheng*1-this.bmJj*1
           //      //this.tableData=tableData
           //    }
           //    if(this.activeName=='second'){
           //      this.bmJj=kesheng;
           //      //this.jjYeTwo=this.jjYeThree*1-this.ygJj*1-this.bmJj*1;
           //      //this.jjYeTwo=this.jjYeThree*1-kesheng*1-this.ygJj*1
           //      //this.tableDataTwo=tableData
           //    }
           //   //console.log("this.bmJj:"+this.bmJj)
           //   //console.log("this.ygJj:"+this.ygJj)
           //    this.jjYe=this.jjYeThree*1-this.bmJj*1-this.ygJj*1;
           //    this.jjYeTwo=this.jjYeThree*1-this.ygJj*1-this.bmJj*1;
           //  }
          //console.log("this.jjYe:"+this.jjYe)
          //console.log("this.jjYeTwo:"+this.jjYeTwo)

        },
        //调用模板为数据
        mubanTableChild(mubanTableChild){
            if(this.activeName=='first'){
                this.tableData=JSON.parse(mubanTableChild[0].fpData)
                this.$refs.renYuanTableRef.muban(value,this.tableData)
                // this.getSpanArr(this.tableData);
                // this.getSpanArrJiang(this.tableData)
            }
            if(this.activeName=='second'){
                this.tableDataTwo=JSON.parse(mubanTableChild[0].fpData)
                this.$refs.buMenTableRef.muban(this.tableDataTwo)
                // this.getSpanArr(this.tableDataTwo);
                // this.getSpanArrJiang(this.tableDataTwo)
            }
           ////console.log("模板:"+JSON.stringify(mubanTableChild))
        },
        //调用模板
        diaoyong(){
            this.$nextTick(()=>{
                var fpType=this.activeName=='first'?0:1;
                this.$refs.mubanTableRef.init(this.jjfpId,fpType)
            })
        },
        //保存为模板
        keepMoBan(){
            this.$prompt('请输入模板名称', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                this.$message.closeAll()
                if(value==""){
                    this.$message.warning("请填写模板名称!")
                    return false
                }
                var params={
                    jjfpId:this.jjfpId,
                    value:value,
                }
                if(this.activeName=='first'){
                    this.$refs.renYuanTableRef.keepMuBan(params)
                }
                if(this.activeName=='second'){
                     this.$refs.buMenTableRef.keepMuBan(params)
                }
                // saveTemplate(params).then(res=>{
                //     if(res.data.code==0){
                //         this.$message({
                //             type: 'success',
                //             message: '模板保存成功!'
                //         });
                //     }
                // })
            }).catch(() => {
                this.$message.closeAll()
            this.$message({
                type: 'info',
                message: '取消输入模板名称'
            });
            });
        },
        //人员与机构分组删除
        renSplice(index){
            var data=this.activeName=='first'?this.tableData:this.tableDataTwo
            data.splice(index,1)
            this.getSpanArr(data);
            this.getSpanArrJiang(data)
        },
        //人员分组选择
        renyuanchange(value){
            this.$refs.renYuanTableRef.jiang(value,this.checkList)
            
        },
        //机构
        jigouchange(value){

            this.$refs.buMenTableRef.jiang(value,this.jigouList)
            
        },
        moreOne(type){

            if(type==1){
                this.colHeightshow = !this.colHeightshow
               //console.log(this.colHeightshow)
                if(this.colHeightshow){
                    this.colHeightOne="auto"
                }else{
                    this.colHeightOne="40px"
                }

            }
            if(type==2){
                this.colHeightshowtwo = !this.colHeightshowtwo
                if(this.colHeightshowtwo){
                    this.colHeightTwo="auto"
                }else{
                    this.colHeightTwo="40px"
                }
            }
            //colHeightshowThree
            if(type==3){
                this.colHeightshowThree = !this.colHeightshowThree
                if(this.colHeightshowThree){
                    this.colHeightThree="auto"
                }else{
                    this.colHeightThree="40px"
                }
            }
        },
        //预分配子集过来
        getChildValue(obj){
            //console.log("预分配子集过来:"+JSON.stringify(obj))
            let zs = 0;
            for (var i in obj) {
                zs += obj[i].ysNumber;
            }
            var num=0
            var tableData=this.activeName=='first'?this.tableData:this.tableDataTwo
            for (let i = 0; i < obj.length; i++) {
                for(let j=0;j<tableData.length;j++){
                    if(obj[i].id==tableData[j].id){
                        tableData[j].jjxJe=obj[i].ysNumber
                        num=j
                    }
                }
            }

           this.$nextTick(()=>{
                this.getSpanArrJiang(tableData);
                if(this.activeName=='first'){
                    this.tableData=tableData
                }
                if(this.activeName=='second'){
                    this.tableDataTwo=tableData
                }
                this.blurJjxje(num)
            })

        },
        //预分配
        yufenpei(){
            this.$message.closeAll()
            if(this.activeName=="first"){
                if(this.multipleSelection.length==0){
                    this.$message.warning("请先选择给哪些人员分组预分配!")
                    return false;
                }
                this.$nextTick(()=>{
                    this.$refs.yufenpeiRef.init(this.multipleSelection,this.activeName)
                })
            }
            if(this.activeName=="second"){
                if(this.multipleSelectionTwo.length==0){
                    this.$message.warning("请先选择给哪些机构分组预分配!")
                    return false;
                }
                this.$nextTick(()=>{
                    this.$refs.yufenpeiRef.init(this.multipleSelectionTwo,this.activeName)
                })
            }
        },
        //从奖金项子集过来
        jiangjinxChild(jiangjinxChild){
            this.jiangVisible=false;
            if(this.activeName=='first'){
                this.tableData=this.tableData.map(item=>{
                    if(item.id==jiangjinxChild.id&&item.jjxId==jiangjinxChild.jjxId){
                        return jiangjinxChild
                    }else{
                        return item
                    }
                })
                this.getSpanArrJiang(this.tableData)
            }
            if(this.activeName=='second'){
                this.tableDataTwo=this.tableDataTwo.map(item=>{
                    if(item.id==jiangjinxChild.id&&item.jjxId==jiangjinxChild.jjxId){
                        return jiangjinxChild
                    }else{
                        return item
                    }
                })
                this.getSpanArrJiang(this.tableDataTwo)
            }
        },
        
        //人员分组筛选
        changeRyfzMc(value){
            if(value!=""){
                var  arr=[]
                this.tableData=this.tableDataOld;
                for(var i in this.tableData){
                    if(this.tableData[i].id==value){
                        arr.push(this.tableData[i])
                    }
                }
                this.tableData=arr;
                this.getSpanArr(this.tableData)
            }else{
                this.tableData=this.tableDataOld;
                this.getSpanArr(this.tableData)
            }

        },
        //奖金项筛选
        changeJjxMc(value){
            if(value!=""){
                var  arr=[]
                this.tableData=this.tableDataOld;
                for(var i in this.tableData){
                    if(this.tableData[i].jjxId==value){
                        arr.push(this.tableData[i])
                    }
                }
                this.tableData=arr;
                this.getSpanArr(this.tableData)
            }else{
                this.tableData=this.tableDataOld;
                this.getSpanArr(this.tableData)
            }
        },
        
        //表头筛选数据方法
        tableFilter(list){ // 传入表格数据
            let filters = {}
            if (list.length) {
            Object.keys(list[0]).forEach(item => { // 拿到第一条数据，将key值组成数组，并将key给filters对象作为键名，值为空数组
                filters[item] = []
            })
            list.forEach(item => { // 遍历表格的数据数组
                for (let key in item) { // 遍历数据数组的每一项(对象)
                if (filters.hasOwnProperty(key) && !filters[key].find(i => i.text == item[key])) { // 如果filters对象中有当前键名（它的值是数组）,并且该数组中不含当前值的对象
                    filters[key].push({text: item[key], value: item[key]}) // filters当前键名对应的值（数组），再push该值组成的对象（el-table筛选条件的格式）
                }
                }
            })
            }
            return filters;
        },
        //人员分组筛选
        filterHandler(value, row, column){
            const property = column['property'];

            return row[property] === value;
        },
        //确认添加完毕
        addConfirm(){
            this.valueList=[]
            // this.toggleSelection()
            // this.multipleSelection=[]
            // this.multipleSelectionTwo=[]
            this.form.bonus=[]
            // this.form.check=[]
             //this.form.jigou=[]
            this.$forceUpdate()
            this.$nextTick(()=>{
                this.$refs.buMenTableRef.qingXuan()
            this.$refs.renYuanTableRef.qingXuan()
            })
            
        },
        fenPei(){
            if(this.activeName=='second'){
                this.jigoujiangjin(this.form.bonus)
                this.form.bonus=[]
            }
            if(this.activeName=='first'){
                this.renyuanjiangjin(this.form.bonus)
                this.form.bonus=[]
            }    
        },
        //选择奖金
        handleCheckedCitiesChange(value){
            if(this.activeName=='first'){
                this.renyuanjiangjin()
            }

            if(this.activeName=='second'){
                this.jigoujiangjin()
            }
            this.form.bonus=[]
            this.form.bonus=value   
        },

        //人员选择奖金
        renyuanjiangjin(value){
            this.$refs.renYuanTableRef.jigoujiangjin(value,this.bonusList)
            
        },
        //机构选择奖金
        jigoujiangjin(value){
              this.$refs.buMenTableRef.jigoujiangjin(value,this.bonusList)  
             
        },
        //去重
        unique(arr){
             for(var i=0; i<arr.length; i++){
                    for(var j=i+1; j<arr.length; j++){
                    if(arr[i].id==arr[j].id&&arr[i].jjxId==arr[j].jjxId){         //第一个等同于第二个，splice方法删除第二个
                        arr.splice(j,1);
                        j--;
                    }
                    }
                }
                return arr;

        },
        toggleSelection(rows) {
            if (rows) {

            rows.forEach(row => {

                if(this.activeName=='first'){
                    this.$refs.multipleTable.toggleRowSelection(row);
                }
                if(this.activeName=='second'){
                    this.$refs.multipleTableTwo.toggleRowSelection(row);
                }
            });
            } else {
                if(this.activeName=='first'){
                    this.$refs.multipleTable.clearSelection();
                }
                if(this.activeName=='second'){
                    this.$refs.multipleTableTwo.clearSelection();
                }
            }
        },
        //获取人员分组数据
        getcheckList(jjDeptId){
            //人员分组
            getRyfzbList(jjDeptId).then(res=>{
                this.checkList=res.data.data.map(item=>{
                     item.jjxMc=""
                     item.jjxId=""
                     item.jjxJe=0
                     item.fzId=item.id
                     item.fzName=item.ryfzMc;
                     item.gsId=2
                     item.gsName=""
                     item.jjxDate=""
                     item.jkjbj=false
                     item.jjWs="1"
                     item.fzInfo=[]
                    return item
                });
                for(var i in this.tableData){
                    for(var j in this.checkList){

                        if(this.checkList[j].id==this.tableData[i].id){
                            this.tableData[i].ryfzMc=this.checkList[j].ryfzMc
                            this.tableData[i].sl=this.checkList[j].sl
                        }
                    }
                }

            })
            //奖金项
            getJjDeptJjx(jjDeptId).then(res=>{
                //console.log("奖金分配:"+JSON.stringify(res))
                this.bonusList=res.data.data
            })
            //机构分组
            getJgfzList(jjDeptId).then(res=>{
                this.jigouList=res.data.data
                this.jigouList=res.data.data.map(item=>{
                     item.jjxMc=""
                     item.jjxId=""
                     item.jjxJe=0
                     item.fzId=item.id
                     item.fzName=item.jgFzName;
                     item.gsId=20
                     item.gsName=""
                     item.jjxDate=""
                     item.jjWs="1"
                     item.fzInfo=[]
                    return item
                });
            })
        },
        //增加人员分组
        add_grouping(e, id) {
            e.stopPropagation();
            this.$nextTick(() => {
                this.$refs.tableForm.init(this.deptId, id);
            });
        },
        // 新增奖金
        addOrUpdateHandle(id) {
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init(id, this.deptId);
            })
        },
        //新增机构分组
        add_jigougrouping(id){
            this.$nextTick(() => {
                this.$refs.jigoutableRef.init(this.deptId, id);
            });
        },
        //添加分组之后刷新
        refreshDataList(refreshDataList){
            this.getcheckList(this.deptId)
            this.getchudata(this.jjfpId)    
        },
        
        handleClick(tab, event){
            // this.multipleSelection=[]
            // this.multipleSelectionTwo=[]
            this.form.bonus=[]
            // this.$refs.multipleTable.clearSelection()
            // this.$refs.multipleTableTwo.clearSelection();

            if(tab.name=='first'){
                // this.getSpanArr(this.tableData)
                // this.getSpanArrJiang(this.tableData)
                
                    
                this.$nextTick(()=>{
                    // this.isRen=!this.isRen
                    this.$refs.renYuanTableRef.init(this.renList,this.jjfpId,this.deptId,tab.name,this.sfCeff,this.gqTime)
                        this.fromJg={
                            jgdsJiang:this.jgdsJiang
                        }
                   ////console.log("this.renList:"+JSON.stringify(this.renList))
                  
                })
                
                    
            }
            if(tab.name=='second'){
                // this.getSpanArr(this.tableDataTwo)
                // this.getSpanArrJiang(this.tableDataTwo)
                this.$nextTick(()=>{
                        // this.isJi=!this.isJi
                    this.$refs.buMenTableRef.init(this.buList,this.jjfpId,this.deptId,tab.name,this.sfCeff,this.gqTime);
                            this.fromRy={
                            rydsJiang:this.rydsJiang
                        }
                       
                })
            }
        },
        //表格多选
        handleSelectionChange(val){
            if(this.activeName=="first"){
                this.multipleSelection=val;
            }
            if(this.activeName=="second"){
                this.multipleSelectionTwo=val;
            }
        },
        //人员分组合并单元格
        getSpanArr(data){
            this.spanArr=[]
            for (var i = 0; i < data.length; i++) {
                if (i === 0) {
                this.spanArr.push(1);
                this.pos = 0;
                } else {
                // 判断当前元素与上一个元素是否相同
                if (data[i].id === data[i - 1].id) {
                    this.spanArr[this.pos] += 1;
                    this.spanArr.push(0);
                } else {
                    this.spanArr.push(1);
                    this.pos = i;
                }
                }

            }
        },
        blurJjxje(index,gsid){
            this.$nextTick(()=>{
                this.$message.closeAll()
                if(gsid==""){
                    this.$message.warning("请先选择计算公式!")
                    return
                }
                this.getnum2()


               if(this.sfCeff=="否"){
                        if((this.num1*1+this.num2*1)>this.jjYeFour){

                            if(this.activeName=="first"){
                                this.tableData[index].jjxJe=0
                            }
                            if(this.activeName=="second"){
                                this.tableDataTwo[index].jjxJe=0
                            }
                            this.getnum2()
                            this.$message.warning("奖金项总和不能超过可剩余金额!")
                        }
                }
                // if(this.activeName=="first"){
                //     this.jjYe=(this.jjYeTwo*1-this.num1*1).toFixed(2)
                //     this.jjYeThree=this.jjYe
                // }
                // if(this.activeName=="second"){
                //     this.jjYe=(this.jjYeThree*1-this.num2*1).toFixed(2)
                //     this.jjYeTwo=this.jjYe
                // }


                if(this.activeName=="first"){
                    this.getSpanArrJiang(this.tableData);
                    //this.jjYe=(this.jjYeThree*1-this.num1*1-this.num2*1-this.bmJj*1).toFixed(2)
                  // this.bmJj=data.bmJj;
                  // this.ygJj=data.ygJj;
                  // this.jjYeTwo=data.fpJj;
                 // this.jjYe=(this.jjYeThree*1-this.bmJj*1-this.num1*1).toFixed(2)
                }
                if(this.activeName=="second"){
                    //this.jjYe=(this.jjYeThree*1-this.num1*1-this.num2*1-this.ygJj*1).toFixed(2);
                  //this.jjYeTwo=(this.jjYeThree*1-this.ygJj*1-this.num2*1).toFixed(2)
                    this.getSpanArrJiang(this.tableDataTwo);
                }
                this.jjYe=(this.jjYeThree*1-this.bmJj*1-this.num1*1).toFixed(2);
                this.jjYeTwo=(this.jjYeThree*1-this.ygJj*1-this.num2*1).toFixed(2)
                this.$forceUpdate()
            })

        },
        getnum2(){
            if(this.activeName=="first"){
                    var list=this.tableData.map(item=>{
                        if(item.gsId==-1){
                            return  item.jjxJe*item.sl*1
                        }else{
                            return item.jjxJe*1
                        }
                    })
                   this.num1= this.sum(list)
                }
                if(this.activeName=="second"){
                    var list=this.tableDataTwo.map(item=>{
                        if(item.gsId==-1){
                            return  item.jjxJe*item.sl*1
                        }else{
                            return item.jjxJe*1
                        }
                    })
                   this.num2= this.sum(list)
                }
        },
        //数组总和
        sum(arr) {
            return arr.reduce(function(prev, curr, idx, arr){
                return prev*1 + curr*1;
            });
        },
        //奖金项合并数据
        getSpanArrJiang(data){
            const endresult = Object.values(data.reduce((value, object) => {

                if (value[object.jjxMc]) {
                    if(data[0].jjxJe==value[object.jjxMc].jjxJe&&value[object.jjxMc].gsId==-1){
                            var temp=value[object.jjxMc].jjxJe*value[object.jjxMc].sl*1;
                            value[object.jjxMc].jjxJe=temp;
                        }

                    if(object.gsId==-1){
                      value[object.jjxMc].jjxJe = (value[object.jjxMc].jjxJe*1+(object.jjxJe*1)*(object.sl*1)).toFixed(2);
                    }else {
                      value[object.jjxMc].jjxJe = (value[object.jjxMc].jjxJe*1+(object.jjxJe*1)).toFixed(2);
                    }
                  //value[object.jjxMc].jjxJe = (value[object.jjxMc].jjxJe*1+(object.jjxJe*1)*(object.sl*1)).toFixed(2);
                } else {
                  value[object.jjxMc] = { ...object}
                  if(object.gsId==-1){
                    value[object.jjxMc].jjxJe=((object.jjxJe*1)*(object.sl*1)).toFixed(2);
                  }else{
                    value[object.jjxMc].jjxJe=(object.jjxJe*1).toFixed(2);
                  }
                }
                return value;
                }, {}));
                this.dataList=endresult

                this.$forceUpdate();
                //console.log(JSON.stringify(endresult))
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {

            if (columnIndex === 0 || columnIndex === 1) {
                const _row = this.spanArr[rowIndex]?this.spanArr[rowIndex]:0;
                const _col = _row > 0 ? 1 : 0;
               //console.log(`rowspan:${_row} colspan:${_col}`);
                return {
                // [0,0] 表示这一行不显示， [2,1]表示行的合并数
                rowspan: _row,
                colspan: _col
                };
            }
        },
        objectSpanMethodJiang({row, column, rowIndex, columnIndex} ){

            if (columnIndex === 0 || columnIndex === 1) {

                const _row = this.spanArrTwo[rowIndex]?this.spanArrTwo[rowIndex]:0;
                const _col = _row > 0 ? 1 : 0;
               //console.log(`rowspan:${_row} colspan:${_col}`);
                return {
                // [0,0] 表示这一行不显示， [2,1]表示行的合并数
                rowspan: _row,
                colspan: _col
                };
            }
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
            if (index === 0) {
                sums[index] = '合计';
                return;
            }

            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
                //console.log(index)
                sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                    return prev + curr;
                } else {
                    return prev;
                }
                }, 0);
                sums[index] += ' 元';
            } else {
                sums[index] = '';
            }

            });



            return sums;
        },

        
        //奖金分配
        bonusDistribution(row){
            this.jiangVisible=true
            this.$nextTick(()=>{
                var params={
                    activeName:this.activeName,
                    row:row
                }
                this.$refs.jiangjinxiangRef.init(params)
            })
            // this.$refs.bonusDistributionRef.init(this.jjfpId)
        },
        //保存
        keepTable(){
            if(this.activeName=='first'){
               // this.putUpdateGrNew()
                var params={
                        ryze:this.ryze,
                        jjYe:this.jjYe,
                        fpId:this.jjfpId,
                }
                this.$refs.renYuanTableRef.putUpdateGrNew(params)
            }
            if(this.activeName=='second'){
               // this.putupdateBmNew()
                var params={
                        jgze:this.jgze,
                        jjYe:this.jjYe,
                        fpId:this.jjfpId,
                }
                this.$refs.buMenTableRef.putupdateBmNew(params)
            }
        },
        //人员保存
        putUpdateGrNew(){
            this.$message.closeAll()
            var list=this.tableData.filter(item=>{
                return item.jjxMc==""
            })
            var gongshi=this.tableData.filter(item=>{
                return item.gsId==""
            })
            if(list.length>0){
                this.$message.warning("存在人员分组未选择奖金项!")
                return false;
            }
            if(gongshi.length>0){
                this.$message.warning("存在人员分组未选择公式!")
                return false;
            }
            var num=this.num1*1+this.num2*1
            var params={
                fpId:this.jjfpId,
                fpData:this.tableData,
                ygJj:num,
                jjYe:this.jjYe
            }
            updateGrNew(params).then(res=>{
                //console.log(JSON.stringify(res))
                if(res.data.code==0){
                    this.$nextTick(()=>{
                        //console.log("this.jjfpId:"+this.jjfpId)
                        this.$refs.renYuanKeepRef.init(this.jjfpId)
                        //this.tableData=[];
                       // this.getSpanArrJiang(this.tableData)
                        this.addConfirm()

                    })
                }

            })
        },
        //机构分组保存
        putupdateBmNew(){
            
        },
        //上传成功
        handleSuccess(response, file, fileList){

        },
        //移除文件时
        handleRemove(response, file, fileList){

        },
        callback(){
            this.tableData=[];
            this.tableDataTwo=[];
           this.dataList=[];
            //this.$refs.multipleTable.clearSelection()
           // this.$refs.multipleTableTwo.clearSelection()
            this.form.bonus=[]
            this.form.check=[]
            this.form.jigou=[]
            this.visible=false
            this.$emit('refreshDataList')
           //console.log("走关闭了么3333")
        },
        callbackTwo(){
            this.jiangVisible=false
            this.$emit('refreshDataList')
        },
    }
}
</script>

<style>

.tableBox table {
        /*设置相邻单元格的边框间的距离*/
    border-spacing: 0;
        /*表格设置合并边框模型*/
        border-collapse: collapse;
        text-align: center;
    }
    /*关键设置 tbody出现滚动条*/
.tableBox table tbody {
        display: block;
        height: 300px;
        overflow-y: scroll;
}

 .tableBox table thead,
  .tableBox tbody tr {
    display: table;
        width: 100%;
        table-layout: fixed;

    }
    /*关键设置：滚动条默认宽度是16px 将thead的宽度减16px*/
.tableBox table thead {
        width: calc( 100% - 1em)
}
.popover-style-parent-div .el-popover{
  width:80%!important;
  background: #f00;
}

</style>
